<script setup>
import {ref, watch, toRefs} from 'vue';
import {Upload as AUpload} from 'ant-design-vue';
import {PlusOutlined} from '@ant-design/icons-vue'
const token =  sessionStorage.getItem("token");

// 图片上传url
const uploadURL = 'http://47.107.231.209:2224/admin/v1/files';

// props
const props = defineProps({
  fileList: {
    // TODO any
    type: Array,
    default: [],
  },

  maxCount: {
    type: Number,
    default: 1,
  },
});
const {fileList} = toRefs(props);

const _fileList = ref(props.fileList);

// 定义事件
const emit = defineEmits(['uploaded', 'change', 'update:fileList']);

// 请求头
const headers = {
  'Authorization': token
};

/**
 * change事件
 * @param params -
 */
const handleChange = (params) => {
  const result = [];
  params.fileList.forEach((item, index) => {
    if (item.status === 'done') {
      if (item.response.code === 0) {
        // 上传成功返回服务器地址
        result.push(item.response.data.path);
      } else {
        _fileList.value[index].status = 'error';
        _fileList.value[index].response = item.response.msg || '上传失败';
      }
    } else if (item.status === 'error') {
      // 上传失败显示原因
      _fileList.value[index].response = typeof item.response === 'object' ? item.response.msg : '上传失败';
    } else if (item.url) {
      result.push(item.url);
    }
  });

  emit('uploaded', result);
  // change被定义了无法透传，这里要手动处理
  emit('change', params);
}

// TODO any
/**
 * v-model:fileList
 * 因为props声明了fileList，失去了v-model特性，在这里手动处理
 * @param fl -
 */
const handleModelFileList = (fl) => {
  _fileList.value = fl;
  emit('update:fileList', fl);
}

watch(fileList, (val) => {
  _fileList.value = val;
});

</script>

<template>
  <AUpload
    name="file"
    list-type="picture-card"
    :action="uploadURL"
    :headers="headers"
    :max-count="maxCount"
    :fileList="_fileList"
    @update:fileList="handleModelFileList"
    @change="handleChange"
    :multiple="maxCount > 1"
  >
    <!-- <template #itemRender="{file}">
      <SImage :src="file.url" />
    </template> -->

    <div v-if="_fileList.length < maxCount">
      <PlusOutlined />
      <div style="margin-top: 8px">添加图片</div>
    </div>
  </AUpload>
</template>

<style scoped>

</style>
